#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <err.h>
#include <cstring>
#include <errno.h>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>

#define ReadOpen 1
#define WriteOpen 2

const std::string gcommfile = "./fifo";

enum
{
    MKFIFO_FILD = 0,
};
class PipeFifo
{
public:
    PipeFifo(const std::string commfile = gcommfile) : _commfile(commfile), mod(0666)
    {
    }
    ~PipeFifo() {}

    // 创建管道
    void Build()
    {
        umask(0);
        if(isExited())
            return;
        int n = mkfifo(_commfile.c_str(), mod);
        if (n < 0)
        {
            std::cerr << "mkfifo fild: " << strerror(errno) << " errno: " << errno << std::endl;
            exit(MKFIFO_FILD);
        }
        std::cerr << "mkfifo success: " << strerror(errno) << " errno: " << errno << std::endl;
    }
    // 获取管道(打开管道)
    //Client(客服端以读打开),Server(服务端以写打开)
    int OpenFile(int OpenFlag)
    {
        int fd;
        if(OpenFlag & ReadOpen)
        {
            fd = open(_commfile.c_str(), O_RDONLY);
        }
        else if (OpenFlag & WriteOpen)
        {
            fd = open(_commfile.c_str(), O_WRONLY);
        }
        else{
            std::cout << "打开方式失败" << std::endl;
        }
        return fd;
    }

    // 删除管道
    void Delete()
    {
        if(!isExited())
            return ;

        //unlink删除文件名与innode之间的映射关系
        unlink(_commfile.c_str());
    }

private:
    bool isExited()
    {
        struct stat statfile;
        int n = stat(_commfile.c_str(), &statfile);
        if (n < 0)
        {
            errno = 0;
            std::cerr << "stat fild" << strerror(errno) << " errno: " << errno << std::endl;
            return false;
        }
        std::cerr << "stat success" << strerror(errno) << " errno: " << errno << std::endl;

        return true;
    }

private:
    std::string _commfile;
    mode_t mod;
};